package com.style.study.juc.c_017_threadpool;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author zhangsan
 * @date 2021/7/10 10:08
 */
public class T_ThredPoolStatus {

    public static void main(String[] args) throws InterruptedException {
        // 状态
//        System.out.println(get());

        // 背压测试
//        test2();

        // i++ , ++i性能测试
        for (int i = 0; i < 10; i++) {
            System.out.println("第" + (i + 1) + "次测试: ");
            test3();
        }
    }

    // shutdown, termination状态
    static String get() throws InterruptedException {
        AtomicReference<String> val = new AtomicReference<>("");
        ThreadPoolExecutor tpe = new ThreadPoolExecutor(1, 1, 1 , TimeUnit.SECONDS,
                new LinkedBlockingQueue<>());

        tpe.submit(() -> {
            System.out.println("hello");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            val.set("执行");
            System.out.println("exit");
        });

        tpe.shutdown();
//        tpe.shutdownNow();
        tpe.awaitTermination(1, TimeUnit.SECONDS);
        return val.get();
    }

    private static void test2() throws InterruptedException {
        ThreadPoolExecutor e = new ThreadPoolExecutor(5, 10, 1, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(10), Thread::new, new RejectedExecutionHandler() {
            @Override
            public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
                if(!e.isShutdown()) {
                    r.run();
                    System.out.println("线程池满了");
                }
            }
        });


        for (int i = 0; i < 21; i++) {
            e.submit(() -> {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException interruptedException) {
                    interruptedException.printStackTrace();
                }
            });
        }

        e.shutdown();
        e.awaitTermination(1, TimeUnit.SECONDS);
    }

    static void test3() {
        int times = 1000_000_000;
        int cnt1 = 0;
        long s1 = System.nanoTime();
        for (int i = 0; i < times; i++) {
            cnt1++;
        }
        long s2 = System.nanoTime();
        System.out.println("i++: " + cnt1 + " 耗时: "+ (s2 - s1) + "ns");


        int cnt2 = 0;
        long s3 = System.nanoTime();
        for (int i = 0; i < times; i++) {
            ++cnt2;
        }
        long s4 = System.nanoTime();
        System.out.println("++i: " + cnt2 + ", 耗时: "+ (s4 - s3) + "ns");
    }
}
